package com.sto.stoapp.activity;

import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.content.DialogInterface;
import android.content.DialogInterface.OnCancelListener;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnKeyListener;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

import com.sto.stoapp.StoApplication;
import com.sto.stoapp.db.StoFilePreference;
import com.sto.stoapp.db.manager.LoginInfoManager;
import com.sto.stoapp.db.manager.SalesSignNameManager;
import com.sto.stoapp.http.MessageType;
import com.sto.stoapp.http.response.TimeSynchResponse;
import com.sto.stoapp.listener.OnBackClickListener;
import com.sto.stoapp.listener.StoOnClickListener;
import com.sto.stoapp.thread.DeleteDataThread;
import com.sto.stoapp.thread.TimeSynchThread;
import com.sto.stoapp.util.Action;
import com.sto.stoapp.util.Helper;
import com.sto.stoapp.widget.BaseActivity;
import com.sto.stoapp.widget.BaseDialog;

import sto.android.app.StoPdaKeyEvent;

public class StoSettingsActivity extends BaseActivity {

	private Button bluetooth, wlan, hotLine, timeSyn, busiSet, barCode;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.sto_settings);
		((TextView) findViewById(R.id.title))
				.setText(R.string.sto_login_settings);
		initWidget();
		initListener();
		hotLine.setVisibility(View.GONE);
	}

	private void initWidget() {
		bluetooth = (Button) findViewById(R.id.blue_settings);
		wlan = (Button) findViewById(R.id.wlan_settings);
		hotLine = (Button) findViewById(R.id.hot_line);
		timeSyn = (Button) findViewById(R.id.time_syn);
		busiSet = (Button) findViewById(R.id.busi_set);
		barCode = (Button) findViewById(R.id.bar_code);
	}

	private void initListener() {
		bluetooth.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				blueToothSet();
			}
		});

		wlan.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				wlanSet();
			}
		});

		timeSyn.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				timeSyn();
			}

		});

		busiSet.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				busiSet();
			}

		});

		barCode.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				barCodeSet();
			}

		});

	}

	private Handler handler = new Handler() {

		@Override
		public void handleMessage(Message msg) {
			super.handleMessage(msg);
			if (msg.what ==MessageType.SYNCH_TIME_TYPE) {
				TimeSynchResponse response = (TimeSynchResponse) msg.obj;
				if (response != null && response.getLongTime() != null) {
					StoApplication.getStoJni().SetSystemTime(response.getLongTime());
					StoFilePreference.getInstance(StoSettingsActivity.this).setPowerOffTime(Long.parseLong(response.getLongTime()));
					StoFilePreference.getInstance(StoSettingsActivity.this)
							.setTimeSynch(true);
					new DeleteDataThread(StoSettingsActivity.this).start();
					Helper.showLongToast(StoSettingsActivity.this,
							getText(R.string.synch_time_success).toString());
				} else {
					// StoFilePreference.getInstance(StoSettingsActivity.this)
					// .setTimeSynch(false);
					showTimeErrorDialog(getText(R.string.synch_time_failure)
							.toString());
				}
			}
		}

	};
	AlertDialog tdialog = null;

	private void showTimeErrorDialog(String str) {

		LayoutInflater flater = LayoutInflater.from(this);
		View view = flater.inflate(R.layout.sto_sales_order_notice, null);
		Builder builder = new AlertDialog.Builder(this);

		TextView msgCancelText = (TextView) view
				.findViewById(R.id.order_notice_detailview);

		msgCancelText.setTextColor(Color.WHITE);

		msgCancelText.setText(str);

		builder.setTitle("提示")
				.setView(view)
				.setPositiveButton(R.string.confirm,
						new DialogInterface.OnClickListener() {

							@Override
							public void onClick(DialogInterface dialog,
									int which) {
								dialog.dismiss();
								tdialog = null;
							}
						});

		tdialog = builder.create();
		tdialog.getWindow().setType(
				(WindowManager.LayoutParams.TYPE_SYSTEM_ALERT));
		tdialog.setCancelable(true);
		tdialog.setOnCancelListener(new OnCancelListener() {

			@Override
			public void onCancel(DialogInterface dialog) {
				tdialog = null;
			}
		});
		tdialog.show();

	}

	private void timeSyn() {
		TimeSynchThread synchThread = new TimeSynchThread(this, handler, true);
		synchThread.start();
	}

	private void busiSet() {
		// TODO Auto-generated method stub
		final BaseDialog dialog = new BaseDialog(this);
		dialog.setMessage(getText(R.string.delete_login_info).toString());
		dialog.show();
		dialog.getvPresentation().setVisibility(View.GONE);
		dialog.getvTitle().setVisibility(View.GONE);
		dialog.setOnBackClickListener(new OnBackClickListener() {

			@Override
			public void onBackClickListener(boolean res) {
				dialog.dismiss();
				if (res) {
					LoginInfoManager.getInstance(StoSettingsActivity.this)
							.deleteAll();
					SalesSignNameManager.getInstance(StoSettingsActivity.this)
							.deleteUserData();
				}
			}
		});
	}

	private void barCodeSet() {
		View view = LayoutInflater.from(this)
				.inflate(R.layout.alert_edit, null);
		final EditText alertText = (EditText) view
				.findViewById(R.id.alert_edit);

		/*
		 * @修改内容：处理虚拟键盘小退
		 * 
		 * @修改人： mgf
		 */
		closeBoard(alertText);
		alertText.setText(StoFilePreference.getInstance(
				StoSettingsActivity.this).getBarCodeNumber());
		alertText.setSelection(alertText.getText().toString().length());

		final BaseDialog dialog = new BaseDialog(this);
		dialog.showLog(view);

		view.findViewById(R.id.yes).setOnClickListener(
				new StoOnClickListener(this) {

					@Override
					public void mHonClick(View view) {
						dialog.dismiss();
						if (alertText.getText().toString().matches("[0-9]+")) {
							StoFilePreference.getInstance(
									StoSettingsActivity.this).setBarCodeNumber(
									alertText.getText().toString());
							Helper.showToast(
									StoSettingsActivity.this,
									StoSettingsActivity.this.getText(
											R.string.save_success).toString());
						} else {
							Helper.showToast(
									StoSettingsActivity.this,
									StoSettingsActivity.this.getText(
											R.string.barcode_error).toString());
						}
					}
				});

		view.findViewById(R.id.no).setOnClickListener(
				new StoOnClickListener(this) {

					@Override
					public void mHonClick(View view) {
						dialog.dismiss();
					}
				});

		alertText.setOnKeyListener(new OnKeyListener() {
			private boolean isBackKey;

			@Override
			public boolean onKey(View v, int keyCode, KeyEvent event) {
				if (alertText.isFocused()) {
					if (event.getAction() == StoPdaKeyEvent.KEYCODE_DPAD_UP) {
						if (keyCode == StoPdaKeyEvent.KEYCODE_DEL
								&& alertText.getText().toString().length() == 0) {
							if (!isBackKey) {
								dialog.dismiss();
								isBackKey = true;
								return true;
							} else {
								isBackKey = false;
								return true;
							}
						}
						if (alertText.getText().toString().length() > 0) {
							isBackKey = true;
							return true;
						}
					}
					return false;
				}
				return false;

			}
		});
	}

	private void wlanSet() {
		Intent wlanIntent = new Intent();
		wlanIntent.setAction(Action.WLAN_ACTION);
		startActivity(wlanIntent);
	}

	private void blueToothSet() {
		Intent intent = new Intent();
		intent.setAction(Action.BLUETOOTH_ACTION);
		startActivity(intent);
	}
}
